const query = require('../../db/index');

// 获取分类
exports.getCategories = async (req, res) => {
    try {
        // 执行 SQL 查询
        const sql = `
            SELECT categories.categoriesId, categories.name AS categoryName, GROUP_CONCAT(article.articleId) AS articleIds
            FROM categories
            LEFT JOIN article ON categories.categoriesId = article.categoriesId
            GROUP BY categories.categoriesId;
        `;
        const categoriesWithArticles = await query(sql);

        // 对查询结果进行进一步处理，将 articleIds 字段从字符串转换为数组
        categoriesWithArticles.forEach(category => {
            if (category.articleIds) {
                category.articleIds = category.articleIds.split(',').map(id => parseInt(id));
            } else {
                category.articleIds = [];
            }
        });

        // 返回成功的响应
        return res.dispatch(200, 'ok', categoriesWithArticles);
    } catch (error) {
        // 如果出错，返回 500 错误
        return res.dispatch(500, "Internal Server Error: Failed to get categories with articles");
    }
};


// 添加分类
exports.addCategories = async (req, res) => {
    try {
        const { name } = req.body;

        // 使用 query 执行 SQL 插入语句
        const sql = "INSERT INTO categories (name) VALUES (?)";
        const values = [name];

        try {
            await query(sql, values);
            // 返回成功的响应
            return res.dispatch(201, "Category added successfully");
        } catch (error) {
            // 如果插入分类出错，返回 500 错误
            return res.dispatch(500, "Internal Server Error: Failed to add category");
        }
    } catch (error) {
        // 如果出现其他错误，返回 500 错误
        return res.dispatch(500, "Internal Server Error");
    }
};

// 删除分类
exports.deleteCategories = async (req, res) => {
    try {
        // 从请求参数中获取分类ID
        const categoriesId = req.query.categoriesId;

        // 如果分类ID不存在，返回 400 错误
        if (!categoriesId) {
            return res.dispatch(400, "Bad Request: Category ID is required");
        }

        // 使用分类ID执行数据库删除操作
        const sql = "DELETE FROM categories WHERE categoriesId = ?";
        const values = [categoriesId];

        await query(sql, values);

        // 返回成功的响应
        return res.dispatch(200, "Category deleted successfully");
    } catch (error) {
        // 如果删除分类出错，返回 500 错误
        return res.dispatch(500, "Internal Server Error: Failed to delete category");
    }
};
